package com.sdgakj.web.manager;

import com.google.common.collect.Maps;
import com.sdgakj.entity.Permission;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumMenuLevel;
import com.sdgakj.service.manager.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value="/permission")
public class PermissionController {
	
	@Autowired
	private PermissionService permissionService;
	
	private static Logger logger = LoggerFactory.getLogger(PermissionController.class);
	
	private static final String PAGE_SIZE = "10";
	
	private static Map<String,String> sortTypes =Maps.newLinkedHashMap();
	
	static {
		sortTypes.put("auto", "自动");
	}

	/**
	 * 查询权限列表
	 * @param pageNumber 页号
	 * @param pageSize   页数
	 * @param sortType   排序字段
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
			ServletRequest request){
		Map<String,Object> searchParams =Servlets.getParametersStartingWith(request, "search_");
		if(searchParams.size()<1){
			searchParams.put("EQ_deltag", "0");
		}
		Page<Permission> permissions =permissionService.getPermissions(searchParams,pageNumber,pageSize,sortType);
		
		model.addAttribute("permissions",permissions);
		model.addAttribute("sortType", sortType);
		model.addAttribute("sortTypes", sortTypes);
		// 将搜索条件编码成字符串，用于排序，分页的URL
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "manager/permissionList";
	}
	
	/**
	 * 跳转新增页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/createform",method=RequestMethod.GET)
	public String addPermission(Model model){
		model.addAttribute("action","create");
		return "manager/permissionForm";
	}
	
	/**
	 * 添加权限
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/create",method=RequestMethod.POST)
	public String createPermission(Permission entity,
							   @RequestParam(value="menu",defaultValue="0")Long menuid,
							   @RequestParam(value="submenu",defaultValue="0")Long submenuid,RedirectAttributes redirectAttributes){
		entity.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		if(0!=menuid){
			entity.setParent(permissionService.getPermissionById(menuid));
		}
		if(0!=submenuid){
			entity.setParent(permissionService.getPermissionById(submenuid));
		}
		permissionService.savePermission(entity);	
		redirectAttributes.addFlashAttribute("message", "添加成功！");
		return "redirect:/permission/list";
	}
	
	/**
	 * 跳转修改页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String updatePermission(@PathVariable("id") Long id,Model model){
		Permission permission =permissionService.getPermissionById(id);
		List<Permission> menuList =new ArrayList<Permission>();  //主菜单的list
		List<Permission> submenuList =new ArrayList<Permission>();//子菜单的list
		if(null !=permission){
			// 子菜单级别要查询主菜单
			if(permission.getType().equals("2")){
				menuList =permissionService.getPermissionByType(EnumMenuLevel.MENU.getCode(),Long.valueOf(-1));
			}
			// 按钮级别要查询主菜单和子菜单
			if(permission.getType().equals("3")){
				menuList =permissionService.getPermissionByType(EnumMenuLevel.MENU.getCode(),Long.valueOf(-1));
				// 子菜单列表
//				Long menuid =permission.getParent().getParent().getId();
//				for(Permission p : menuList){
//					if(p.getId().equals(menuid)){
//						submenuList =p.getChildren();
//					}
//				}
				submenuList =permissionService.getPermissionByType(EnumMenuLevel.SUBMENU.getCode(),permission.getParent().getParent().getId());
				
			}
		}
		model.addAttribute("menuList", menuList);
		model.addAttribute("submenuList",submenuList);
		model.addAttribute("permission", permission); //当前要修改的权限
		model.addAttribute("action", "update");
		return "manager/permissionUpdate";
	}
	
	/**
	 * 更新权限
	 * @param Source
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String updatePermission(@ModelAttribute("permission")Permission entity,
							   @RequestParam(value="menu",defaultValue="0")Long menuid,
							   @RequestParam(value="submenu",defaultValue="0")Long submenuid,RedirectAttributes redirectAttributes){
//		entity.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		if(0!=menuid){
			entity.setParent(permissionService.getPermissionById(menuid));
		}
		if(0!=submenuid){
			entity.setParent(permissionService.getPermissionById(submenuid));
		}
		permissionService.savePermission(entity);	
		redirectAttributes.addFlashAttribute("message", "修改成功！");
		return "redirect:/permission/list";
	}
	
	/**
	 * 删除权限信息
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)
	public String delete(@PathVariable("id") Long id,RedirectAttributes redirectAttributes){
		Permission permission =permissionService.getPermissionById(id);
		permission.setDeltag(EnumIsDelete.DELETED.getCode()); //设置已经删除
		permissionService.savePermission(permission);
		redirectAttributes.addFlashAttribute("message", "删除成功！");
		return "redirect:/permission/list";
	}
	
	/**
	 * 恢复权限信息
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/recover/{id}",method=RequestMethod.GET)
	public String recover(@PathVariable("id") Long id,RedirectAttributes redirectAttributes){
		Permission permission =permissionService.getPermissionById(id);
		permission.setDeltag(EnumIsDelete.NOTDELETE.getCode()); //设置已经删除
		permissionService.savePermission(permission);
		redirectAttributes.addFlashAttribute("message", "恢复成功！");
		return "redirect:/permission/list";
	}
	
	/**
	 * 更新权限信息
	 * @param entity
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.GET)
	public String update(@Valid @ModelAttribute("permission")Permission entity,RedirectAttributes redirectAttributes){
		permissionService.updatePermission(entity);
		redirectAttributes.addFlashAttribute("message", "更新信息成功");
		return "redirect:/permission/list";
	}
	
	
	@ModelAttribute
	public void getPermission(@RequestParam(value ="id",defaultValue = "-1")Long id ,Model model){
		if(id != -1){
			model.addAttribute("permission", permissionService.getPermissionById(id));
		}
	}
	
	/**
	 * ajax获取主菜单
	 * @param level
	 * @param pid
	 * @return
	 */
	@RequestMapping(value="/getmenu",method=RequestMethod.GET)
	@ResponseBody
	public List<Permission> getRoot(@RequestParam("type")String type,
									@RequestParam(value="pid",defaultValue="-1")Long pid){
		List<Permission> permissionList =permissionService.getPermissionByType(type,pid);
		return permissionList;
	}
	
}
